package com.youlai.jdk;

import org.junit.jupiter.api.Test;

/**
 * 发行日期：2020年9月
 * Java15新增特性
 * Sealed Classes和Interfaces
 * Text Blocks的改进
 * Record的改进
 * @author zc
 * @date 2023-03-25 21:46
 */
public class Java15 {

    /**
     * Sealed Classes和Interfaces
     * 1. 限制类的继承
     * 2. 限制接口的实现
     * 使用permits关键字指明它的子类只能是Circle、Rectangle和Square。这意味着我们不能再定义其他的Shape子类
     */
    public sealed class Shape permits Circle, Rectangle {
        public Shape() {
        }
    }

    public final class Circle extends Shape {
        public Circle() {
        }
    }

    public final class Rectangle extends Shape {
        public Rectangle() {
        }
    }

    /**
     * Text Blocks的改进
     * 持嵌入表达式和转义序列
     */
    @Test
    public void textBlocks() {
        String message = """
    Hello,
    This is a multiline string
    with an embedded expression: %d
    And it also supports escaping: \"""
    """;
        System.out.println(String.format(message, 42));
    }

    /**
     * Record的改进
     * 支持继承和实现接口
     */
    @Test
    public void records() {
        Person person = new Employee("John", 1000);
        System.out.println(person.getName());
    }
    public interface Person {
        String getName();
    }
    public record Employee(String name, double salary) implements Person {
        public Employee {
            if (salary < 0) {
                throw new IllegalArgumentException("Salary cannot be negative");
            }
        }

        public String getName() {
            return name;
        }
    }

}
